package com.leoandroid.tool.toolsbox.largeread.fragment;

import static android.app.Activity.RESULT_OK;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.leoandroid.tool.toolsbox.largeread.activity.ImagePreviewActivity;
import com.leoandroid.tool.toolsbox.largeread.activity.RulerActivity;
import com.leoandroid.tool.toolsbox.largeread.R;
import com.leoandroid.tool.toolsbox.largeread.activity.SurfaceCameraActivity;
import com.leoandroid.tool.toolsbox.largeread.utils.FlashlightUtils;
import com.leoandroid.tool.toolsbox.largeread.utils.SPUtil;

public class MagnifierFragment extends Fragment {

    public static final String TAG = "MagnifierFragment>>";
    private View v;
    private TextView tvMagnifier;
    private TextView tvTorch;
    private TextView tvMultiFun;
    private TextView tvMagnifyImage;
    private ImageView imgTorchStatus;
    private ImageView imgTorch;
    private FrameLayout chiziFl;
    private static final int IMAGE_REQUEST_CODE = 100;
    private boolean isLighOn = false;
    String[] cameraPer = new String[]{Manifest.permission.CAMERA};
    String[] storagePer = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
    public static final int requestCode_Camera = 1;
    public static final int requestCode_storage = 2;


    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.fragment_magnifier, container, false);

        initView();
        return v;
    }

    private void initView(){

        tvMagnifier = v.findViewById(R.id.magnifier);
        tvTorch = v.findViewById(R.id.torch);
        tvMultiFun = v.findViewById(R.id.tv_multi_fun);
        imgTorchStatus = v.findViewById(R.id.ing_torch_status);
        imgTorch = v.findViewById(R.id.img_torch);
        tvMagnifyImage = v.findViewById(R.id.magnify_image);
        chiziFl = v.findViewById(R.id.chiziFl);
        tvMagnifier.setOnClickListener(view -> {
            boolean cameraDenied = SPUtil.with(getActivity()).load().read("CAMERA_DENIED",false);
            if(cameraDenied){
                Toast.makeText(getActivity(),"没有相机授权，功能使用受限,请先授权",Toast.LENGTH_SHORT).show();
                return;
            }
            boolean camera = SPUtil.with(getActivity()).load().read("CAMERA",false);
            if(!camera){
                //申请相机权限
                ActivityCompat.requestPermissions(getActivity(), cameraPer, requestCode_Camera);
                return;
            }
            jumpCamera();
        });

        tvTorch.setOnClickListener(view -> {
            if(!isLighOn){
                turnOnFlash();
            }else{
                turnOffFlash();
            }
        });
        tvMultiFun.setOnClickListener(view -> {
//            Intent intent = new Intent(getContext(), MultiFunctionActivity.class);
//            startActivity(intent);
            Intent intent = new Intent(Settings.ACTION_DISPLAY_SETTINGS);
            startActivity(intent);
        });

        tvMagnifyImage.setOnClickListener(view -> {
            boolean storageDenied = SPUtil.with(getActivity()).load().read("STORAGE_DENIED",false);
            if(storageDenied){
                Toast.makeText(getActivity(),"没有存储权限，功能使用受限,请先授权",Toast.LENGTH_SHORT).show();
                return;
            }
            boolean store = SPUtil.with(getActivity()).load().read("STORAGE",false);
            if(!store){
                //申请相机权限
                ActivityCompat.requestPermissions(getActivity(), storagePer, requestCode_storage);
                return;
            }
         jumpPic();
        });
        chiziFl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent it = new Intent(getActivity(), RulerActivity.class);
                getActivity().startActivity(it);
            }
        });
    }


    // Turning On flash
    private void turnOnFlash() {
        FlashlightUtils.linghtOn();
        toggleBgImage();
        isLighOn = true;
    }

    // Turning Off flash
    private void turnOffFlash() {
        FlashlightUtils.linghtOff();
        toggleBgImage();
        isLighOn = false;
    }

    private void toggleBgImage() {
        if (!isLighOn) {
            imgTorch.setImageResource(R.mipmap.group_switch_flashlight_on);
            imgTorchStatus.setImageResource(R.mipmap.ic_enlarge_flashlight_on);
        } else {
            imgTorch.setImageResource(R.mipmap.group_switch_flashlight_off);
            imgTorchStatus.setImageResource(R.mipmap.ic_enlarge_flashlight_off);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        //在相册里面选择好相片之后调回到现在的这个activity中
        switch (requestCode) {
            case IMAGE_REQUEST_CODE://这里的requestCode是我自己设置的，就是确定返回到那个Activity的标志
                if (resultCode == RESULT_OK) {//resultcode是setResult里面设置的code值
                    try {
                        Uri selectedImage = data.getData(); //获取系统返回的照片的Uri
                        String[] filePathColumn = {MediaStore.Images.Media.DATA};
                        Cursor cursor = getContext().getContentResolver().query(selectedImage,
                                filePathColumn, null, null, null);//从系统表中查询指定Uri对应的照片
                        cursor.moveToFirst();
                        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                        String path = cursor.getString(columnIndex);  //获取照片路径
                        cursor.close();
                        Intent intent = new Intent(getContext(), ImagePreviewActivity.class);
                        intent.putExtra("path", path);
                        startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
        }
    }


    public void onFragmentRequestPermissionResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 1:
                if(ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED){
                    //拒绝相机权限
                    SPUtil.with(getActivity()).load().save("CAMERA",false);
                    SPUtil.with(getActivity()).load().save("CAMERA_DENIED",true);
                    Log.d(TAG,"拒绝相机权限");
                } else {
                    SPUtil.with(getActivity()).load().save("CAMERA",true);
                    jumpCamera();
                    Log.d(TAG,"同意相机权限");
                }
                break;
            case 2:
                if(ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED){
                    //拒绝存储权限
                    SPUtil.with(getActivity()).load().save("STORAGE",false);
                    SPUtil.with(getActivity()).load().save("STORAGE_DENIED",true);
                    Log.d(TAG,"拒绝存储权限");
                } else {
                    SPUtil.with(getActivity()).load().save("STORAGE",true);
                    jumpPic();
                    Log.d(TAG,"同意存储权限");
                }
                break;
        }
    }

    public void jumpCamera(){
        Intent intent = new Intent(getContext(), SurfaceCameraActivity.class);
        startActivity(intent);
    }

    public void jumpPic(){
        //在这里跳转到手机系统相册里面
        Intent intent = new Intent(
                Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, IMAGE_REQUEST_CODE);
    }
}
